package com.guldan.thrall.web.controller;

import com.alibaba.fastjson.JSON;
import com.guldan.core.dubbo.client.ResponseDTO;
import com.guldan.core.enums.FileTypeEn;
import com.guldan.core.exception.BusinessException;
import com.guldan.core.response.ResponseJson;
import com.guldan.jaina.dto.citizeninfo.CitizenInfoDTO;
import com.guldan.jaina.dto.progress.BarDTO;
import com.guldan.jaina.dto.register.RegisterTemplateDataDTO;
import com.guldan.jaina.dto.register.RegisterTemplateXlsDTO;
import com.guldan.jaina.provider.ICitizenInfoProvider;
import com.guldan.jaina.provider.IProjectRegisterProvider;
import com.guldan.jaina.provider.ITestProvider;
import com.guldan.thrall.common.base.BaseController;
import com.guldan.thrall.util.CitizenUploadExcel;
import com.guldan.thrall.util.RegisterExcel;
import com.guldan.thrall.util.Uploader;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by Silas.
 * Date: 2016/12/11
 * Time: 12:35
 */
@Controller
@RequestMapping("/test")
public class TestController extends BaseController {

    @Autowired
    private ITestProvider iTestProvider;

    @Autowired
    private ICitizenInfoProvider iCitizenInfoProvider;

    @RequestMapping(value = "/getCustomException", method = RequestMethod.GET)
    @ResponseJson
    public String getCustomException() throws Exception {

        ResponseDTO<String> responseDTO = iTestProvider.getCustomException();
        if (responseDTO.isSuccess())
            return responseDTO.getData();
        else {
            throw responseDTO.getException();
        }
    }

    @RequestMapping(value = "/testExexl", method = RequestMethod.GET)
    @ResponseJson
    public String testExexl() throws Exception {


        String path = "F:\\111.xls";

        for (int i = 0; i < 10; i++) {
            List<CitizenInfoDTO> list = null;
            CitizenUploadExcel excel = new CitizenUploadExcel();
            try {
                list = excel.readExcel(path);
                if (list != null && list.size() > 0) {
                    logger.info(JSON.toJSONString(list));
                }
            } catch (IOException | BusinessException e) {
                // TODO Auto-generated catch block
                logger.info(e.getMessage());
                e.printStackTrace();
            }
            ResponseDTO<BarDTO> response = iCitizenInfoProvider.uploadCitizen(list);
            logger.info("run " + i + " response: " + JSONObject.fromObject(response.getData()).toString());
        }
        return "aa";

    }


    @Autowired
    private IProjectRegisterProvider iProjectRegisterProvider;

    @RequestMapping(value = "/testExexl2", method = RequestMethod.GET)
    @ResponseJson
    public String testExexl2() throws Exception {


        String path = "F:\\222.xls";

        for (int i = 0; i < 10; i++) {

            RegisterTemplateXlsDTO xlsDto = null;
            RegisterExcel excel = new RegisterExcel();
            try {
                xlsDto = excel.readExcel(path);
                List<RegisterTemplateDataDTO> list = xlsDto.getList();
                if (list != null && list.size() > 0) {
                    logger.info(JSON.toJSONString(list));
                }
            } catch (IOException | BusinessException e) {
                // TODO Auto-generated catch block
                logger.info(e.getMessage());
                e.printStackTrace();

            }

            logger.info("down：" + xlsDto.getHeader().toString());

            //call dubbo
            ResponseDTO<BarDTO> response = iProjectRegisterProvider.uploadCitizen(xlsDto.getHeader(), xlsDto.getList());


            logger.info("run " + i + " response: " + JSONObject.fromObject(response.getData()).toString());
        }
        return "aa";

    }


    @RequestMapping(value = "/redisData", method = RequestMethod.GET)
    @ResponseJson
    public Boolean redisData() throws Exception {

        ResponseDTO<Boolean> responseDTO = iTestProvider.redisData();
        if (responseDTO.isSuccess())
            return responseDTO.getData();
        else {
            throw responseDTO.getException();
        }
    }




    @RequestMapping(value = "/checkCitizen", method = RequestMethod.GET)
    @ResponseJson
    public String checkCitizen() throws Exception {

        ResponseDTO<String> responseDTO = iTestProvider.checkCitizen();
        if (responseDTO.isSuccess())
            return responseDTO.getData();
        else {
            throw responseDTO.getException();
        }
    }

    @RequestMapping(value = "/bigDataObject", method = RequestMethod.GET)
    @ResponseJson
    public String bigDataObject(HttpServletRequest request,
                                HttpServletResponse response) throws Exception {


        String s = request.getParameter("s");

        ResponseDTO<String> responseDTO = iTestProvider.bigDataObject(s);
        if (responseDTO.isSuccess())
            return responseDTO.getData();
        else {
            throw responseDTO.getException();
        }
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseJson
    public String down(HttpServletRequest request,
                       HttpServletResponse response) throws Exception {

        response.setCharacterEncoding("utf-8");

        String fileName = "";
        String filePath = "";
        if (request.getParameter("fileName") != null) {
            fileName = request.getParameter("fileName");
        }
        if (request.getParameter("type") != null) {
//            filePath = java.net.URLEncoder.encode(request.getParameter("filePath"), "UTF-8");
            filePath = FileTypeEn.toEnum(Integer.parseInt(request.getParameter("type"))).getMean();
        }

        try {
            String path = request.getRealPath("/") + filePath + fileName;

            logger.info("path: " + path);
            logger.info("filename: " + fileName);

            InputStream inputStream = new FileInputStream(new File(path));

            response.setContentType("application/x-download");// multipart/form-data
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + java.net.URLEncoder.encode(fileName, "UTF-8"));

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

            // 这里主要关闭。
            os.close();

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  返回值要注意，要不然就出现下面这句错误！
        //java+getOutputStream() has already been called for this response
        return null;
    }


    //图片上传
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    @ResponseJson
    public
    @ResponseBody
    String uploadfile(HttpServletRequest request,
                      HttpServletResponse response) throws Exception {

        //request.setCharacterEncoding("utf-8");
        /*response.setHeader("Content-Type", "text/html");

        String rootPath = request.getRealPath("/");

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(Integer.parseInt(new ActionEnter(request, rootPath).exec()));
        } catch (IOException e) {
            e.printStackTrace();
        }*/


        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            logger.info("sssss");
        }

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Uploader up = new Uploader(request);
        String filePath = request.getRealPath("/") + "resources/attachment/citizen/updatearea/up";

        up.setSavePath(filePath);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload();

        String callback = request.getParameter("callback");

        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize() + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";

        result = result.replaceAll("\\\\", "\\\\");
        logger.info("result : " + result);
        if (callback == null) {

            response.getWriter().print(result);

        } else {

            response.getWriter().print("<script>" + callback + "(" + result + ")</script>");
        }

        return result;
    }

    @RequestMapping("/map")
    public String index() {
        return "map";
    }

    @RequestMapping(value = "/createDatav", method = RequestMethod.GET)
    @ResponseJson
    public String createDatav(HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        iTestProvider.createDataV();
        return "true";
    }

    @RequestMapping(value = "/createMysqlData", method = RequestMethod.GET)
    @ResponseJson
    public String createMysqlData(HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        String divisionCode = request.getParameter("divisionCode");
        if (StringUtils.isBlank(divisionCode))
            return "false";
        return iTestProvider.createMysqlData(divisionCode).toString();
    }


}
